import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:life_service/color/hex.dart';
import 'package:life_service/extensions/ex_widget.dart';
import 'package:life_service/route/index.dart';
import 'package:life_service/ui/draw_under_line.dart';
import 'package:life_service/utils/styles.dart';
import 'package:life_service/utils/tools.dart';
import '../controller.dart';

class MineWalletRechargePage extends GetView<MineWalletRechargeController> {
  const MineWalletRechargePage({super.key});

  Widget buildMain(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(Get.mediaQuery.padding.top + 44),
        child: AnnotatedRegion<SystemUiOverlayStyle>(
          value: SystemUiOverlayStyle.dark,
          child: Container(
            padding: Get.mediaQuery.padding,
            alignment: Alignment.centerLeft,
            decoration: BoxDecoration(
              color: Colors.white,
              border: Border(
                bottom: BorderSide(
                  color: HexColor(HexColor.colorF2f2),
                ),
              ),
            ),
            child: TextButton(
              onPressed: Get.back,
              child: Text.rich(
                TextSpan(
                  children: [
                    const WidgetSpan(
                      child: Icon(
                        CupertinoIcons.chevron_back,
                        size: 18,
                        color: Colors.black,
                      ),
                    ),
                    TextSpan(
                      text: ' 充值',
                      style: StylesUtils.customTextStyle(
                        fontSize: StylesUtils.fontSize16,
                        color: HexColor.color3333,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
      body: SingleChildScrollView(
        padding: EdgeInsets.symmetric(
            horizontal: (Get.width - 334) / 2, vertical: 10),
        child: Column(
          children: [
            DrawUnderLine(
              child: SizedBox(
                height: 50,
                child: Row(
                  children: [
                    Container(
                      width: 100,
                      alignment: Alignment.centerLeft,
                      child: Text(
                        '充值金额',
                        style: StylesUtils.customTextStyle(
                          color: HexColor.color3333,
                        ),
                      ),
                    ),
                    Center(
                      child: TextField(
                        style: StylesUtils.customTextStyle(
                          color: HexColor.color3333,
                        ),
                        keyboardType: TextInputType.number,
                        decoration: InputDecoration(
                          hintText: '请输入充值金额',
                          hintStyle: StylesUtils.customTextStyle(
                            color: HexColor.color9999,
                          ),
                          border: InputBorder.none,
                          focusedBorder: InputBorder.none,
                          constraints: const BoxConstraints.expand(
                              width: 210, height: 44),
                          contentPadding: const EdgeInsets.symmetric(
                              vertical: 10, horizontal: 10),
                          isCollapsed: true,
                          isDense: true,
                        ),
                      ),
                    )
                  ],
                ),
              ),
            ),
            DrawUnderLine(
              child: SizedBox(
                height: 50,
                child: Row(
                  children: [
                    Container(
                      width: 100,
                      alignment: Alignment.centerLeft,
                      child: Text(
                        '充值金额',
                        style: StylesUtils.customTextStyle(
                          color: HexColor.color3333,
                        ),
                      ),
                    ),
                    Expanded(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            '工商银行储蓄卡',
                            style: StylesUtils.customTextStyle(
                              color: HexColor.color3333,
                            ),
                          ),
                          IconButton(
                            onPressed: () {
                              openSelectedBankCard(context);
                            },
                            icon: Icon(
                              CupertinoIcons.chevron_forward,
                              size: 20,
                              color: HexColor(HexColor.color3333),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Container(
              height: 44,
              margin: const EdgeInsets.only(top: 15),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(4),
                color: HexColor(HexColor.colorFf62),
              ),
              alignment: Alignment.center,
              child: Text(
                '确认充值',
                style: StylesUtils.customTextStyle(
                  fontSize: StylesUtils.fontSize16,
                ),
              ),
            ).onTap(() async {
              String? result =
                  await Navigator.of(context).push(PayPwdDialog<String>());
              if (result != null && result.length == 6) {
                Get.toNamed(Routes.mineWalletComplete);
              }
            })
          ],
        ),
      ),
    );
  }

  void openSelectedBankCard(BuildContext context) {
    showModalBottomSheet(
      context: context,
      barrierColor: HexColor.rgba(0, 0, 0, 0.4),
      backgroundColor: Colors.white,
      constraints: const BoxConstraints.expand(height: 310),
      useSafeArea: true,
      enableDrag: false,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(36),
          topRight: Radius.circular(36),
        ),
      ),
      builder: (context) {
        return SizedBox(
          height: 310,
          child: Column(
            children: [
              Stack(
                children: [
                  Container(
                    height: 60,
                    alignment: Alignment.center,
                    child: Text(
                      '选择充值方式',
                      style: StylesUtils.customTextStyle(
                        fontWeight: FontWeight.w700,
                        color: HexColor.color3333,
                        fontSize: StylesUtils.fontSize16,
                      ),
                    ),
                  ),
                  Positioned(
                    width: 60,
                    top: 0,
                    right: 0,
                    bottom: 0,
                    child: IconButton(
                      onPressed: Get.back,
                      icon: Icon(
                        CupertinoIcons.xmark,
                        size: 20,
                        color: HexColor(HexColor.colorCccc),
                      ),
                    ),
                  ),
                ],
              ),
              Expanded(
                child: ListView(
                  itemExtent: 50,
                  padding:
                      EdgeInsets.symmetric(horizontal: (Get.width - 334) / 2),
                  children: controller.banks
                      .map(
                        (bank) => Obx(
                          () => DrawUnderLine(
                            child: SizedBox(
                              height: 50,
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Text.rich(
                                    TextSpan(
                                      children: [
                                        WidgetSpan(
                                          child: ToolsUtils.image(
                                              'bank/${bank.value.icon}',
                                              width: 25,
                                              height: 25),
                                          alignment:
                                              PlaceholderAlignment.middle,
                                        ),
                                        TextSpan(
                                          text: ' ${bank.value.name}',
                                          style: StylesUtils.customTextStyle(
                                            color: HexColor.color3333,
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                  IconButton(
                                    onPressed: () {
                                      for (var r in controller.banks) {
                                        if (r == bank) {
                                          r.update(
                                              (row) => row?.checked = true);
                                        } else {
                                          r.update(
                                              (row) => row?.checked = false);
                                        }
                                      }
                                      Get.back();
                                    },
                                    icon: bank.value.checked
                                        ? Icon(
                                            CupertinoIcons
                                                .checkmark_alt_circle_fill,
                                            size: 20,
                                            color: HexColor('#00CC99'),
                                          )
                                        : Icon(
                                            CupertinoIcons.circle,
                                            size: 20,
                                            color: HexColor(HexColor.color9999),
                                          ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ),
                      )
                      .toList(),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return buildMain(context);
  }
}

class PayPwdDialog<T> extends PopupRoute<T> {
  @override
  Color? get barrierColor => Colors.black.withAlpha(0x50);

  @override
  bool get barrierDismissible => true;

  @override
  Duration get transitionDuration => const Duration(milliseconds: 300);

  @override
  String? get barrierLabel => '支付密码';

  final TextEditingController _textEditingController = TextEditingController();
  final FocusNode _textNode = FocusNode();

  final _result = ''.obs;

  @override
  Widget buildPage(BuildContext context, Animation<double> animation,
      Animation<double> secondaryAnimation) {
    return Center(
      child: Material(
        borderRadius: BorderRadius.circular(10),
        color: Colors.white,
        child: Container(
          width: 290,
          height: 190,
          padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 15),
          child: Column(
            children: [
              Stack(
                children: [
                  Container(
                    height: 40,
                    alignment: Alignment.center,
                    child: Text(
                      '请输入支付密码',
                      style: StylesUtils.customTextStyle(
                        fontSize: StylesUtils.fontSize16,
                        color: HexColor.color3333,
                        fontWeight: FontWeight.w700,
                      ),
                    ),
                  ),
                  Positioned(
                    width: 30,
                    top: 0,
                    right: 0,
                    bottom: 0,
                    child: IconButton(
                      onPressed: Get.back,
                      icon: Icon(
                        CupertinoIcons.xmark,
                        size: 20,
                        color: HexColor(HexColor.colorCccc),
                      ),
                    ),
                  )
                ],
              ),
              Container(
                padding: const EdgeInsets.symmetric(vertical: 15),
                alignment: Alignment.center,
                child: Text(
                  '支付金额',
                  style: StylesUtils.customTextStyle(
                    color: HexColor.color9999,
                  ),
                ),
              ),
              Container(
                alignment: Alignment.center,
                padding: const EdgeInsets.only(bottom: 20),
                child: Text(
                  '￥900',
                  style: StylesUtils.customTextStyle(
                    fontSize: StylesUtils.fontSize16,
                    color: HexColor.color3333,
                  ),
                ),
              ),
              TextField(
                controller: _textEditingController,
                focusNode: _textNode,
                keyboardType: TextInputType.number,
                inputFormatters: <TextInputFormatter>[
                  LengthLimitingTextInputFormatter(6),
                  FilteringTextInputFormatter.digitsOnly
                ],
                onChanged: (value) {
                  _result.value = value;
                  if (value.length == 6) {
                    Get.engine.addPostFrameCallback((_) {
                      _textNode.unfocus();
                      Get.back(result: _result.value);
                    });
                  }
                },
              ).offstage(offstage: true),
              GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  _textNode.requestFocus();
                },
                child: Obx(() {
                  return buildNumberWidget(_result.value.length);
                }),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget buildNumberWidget(int length) {
    return CustomPaint(
      painter: _PayPwdCustomPainter(45),
      child: Row(
        children: [
          for (var i = 0; i < 6; i++)
            Expanded(
              child: i < length
                  ? Container(
                      height: 45,
                      alignment: Alignment.center,
                      child: Text(
                        '●',
                        style: StylesUtils.customTextStyle(
                          color: HexColor.color3333,
                          fontSize: StylesUtils.fontSize16,
                        ),
                      ),
                    )
                  : Container(
                      height: 45,
                      alignment: Alignment.center,
                    ),
            ),
        ],
      ),
    );
  }
}

class _PayPwdCustomPainter extends CustomPainter {
  final double height;

  _PayPwdCustomPainter(this.height);

  @override
  void paint(Canvas canvas, Size size) {
    var paint = Paint()
      ..isAntiAlias = true
      ..style = PaintingStyle.stroke
      ..strokeWidth = 0.5
      ..color = Colors.black12;
    Rect rect = Offset.zero & size;
    const radius = Radius.circular(4);
    final path = Path()
      ..addRRect(
        RRect.fromRectAndRadius(rect, radius),
      );

    canvas.drawPath(path, paint);
    double w = size.width / 6;
    for (var i = 1; i < 6; i++) {
      canvas.drawLine(Offset(w * i, 0), Offset(w * i, height), paint);
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}
